package qeug.shsh.facde.controller;

import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.operate.OperateOptionConst;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.openapi.common.custom.annotation.ApiController;
import kd.bos.openapi.common.custom.annotation.ApiPostMapping;
import kd.bos.openapi.common.custom.annotation.ApiRequestBody;
import kd.bos.openapi.common.custom.annotation.ApiResponseBody;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.devportal.BizScriptServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import qeug.shsh.facde.info.AuditDataV2;
import qeug.shsh.facde.resultext.ApprovalResultV2ResultExt;
import qeug.shsh.facde.resultext.CustomerResultExt;
import qeug.shsh.helper.FacadeHelper;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;

/**
 * @projectName: qeug-cosmic-root-project
 * @package: qeug.shsh.facde.controller
 * @className: ApprovalResultV2Controller
 * @author: xuhaihui
 * @description: TODO
 * @date: 2025/1/14 16:09
 * @version: 1.0
 * //说明：付款申请单、借款单、资金计划、资金计划调整单BPM审批回传接口（新）
 */
@ApiController(value = "ApprovalResultV2Controller", desc = "BPM结果回传接口(新)")
public class ApprovalResultV2Controller implements Serializable {
    @ApiPostMapping(value = "/ApprovalResultV2", desc = "BPM结果回传接口(新)")
    public CustomApiResult<@ApiResponseBody("返回参数") ApprovalResultV2ResultExt> result_audit_v2
            (@NotNull @Valid @ApiRequestBody(value = "入参") AuditDataV2 auditModel) {
        ApprovalResultV2ResultExt ApprovalResultV2Result = new ApprovalResultV2ResultExt();
        OperateOption operateOption = OperateOption.create();
        operateOption.setVariableValue("ignoreValidation", String.valueOf(true));//绕过网络互斥操作

        HashMap<String, Object> auditLog = new HashMap<>();
        String dataId = auditModel.getDataId();// 单据编号
        String dataVersion = auditModel.getDataVersion();// 单据版本号
        String processName = auditModel.getProcessName();// 流程名
        int incident = auditModel.getIncident();// 实例号
        String bpm = auditModel.getBpm();// 流程名+实例号
        String initiatorName = auditModel.getInitiatorName();//流程发起人
        String currentUserName = auditModel.getCurrentUserName();// 当前审批人
        int appResult = auditModel.getAppResult();// 审批状态
        if (appResult == 0) {
            auditLog.put("appResult", "审批中");
        } else if (appResult == 1) {
            auditLog.put("appResult", "审批完成");
        } else if (appResult == 3) {
            auditLog.put("appResult", "审批不同意");
        }

        String entityName = null;
        switch (processName) {
            case "CCSZiJinJHSQ":
                entityName = "qeug_fundplan";//资金计划
                DynamicObject qeug_fundplan = BusinessDataServiceHelper.loadSingle("qeug_fundplan", "billno", new QFilter("billno", "=", dataId).toArray());
                if (qeug_fundplan == null) {
                    //资金计划中找不到对应的单据，便是资金计划调整
                    entityName = "qeug_fundadjust";//资金计划调整
                }
                break;
            case "CCSFuKuanSQ":
                entityName = "er_publicreimbursebill";//付款申请
                DynamicObject er_publicreimbursebill = BusinessDataServiceHelper.loadSingle("er_publicreimbursebill", "billno", new QFilter("billno", "=", dataId).toArray());
                if (er_publicreimbursebill == null) {
                    //付款申请单中找不到对应的单据，便是借款单
                    entityName = "er_dailyloanbill";//借款单
                }
                break;
        }
        QFilter[] a = new QFilter[]{new QFilter("billno", "=", dataId)
                , new QFilter("qeug_processinstance", "=", Integer.toString(incident))};//单据信息：通过编码和实例号查询单据信息
        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(entityName, a);
        if (dynamicObject == null) {
            //找不到对应的单据
            ApprovalResultV2Result.setSuccess(false);
            ApprovalResultV2Result.setData("找不到对应的单据！");
            return CustomApiResult.success(ApprovalResultV2Result);
        }

        //记录接口日志
        auditLog.put("dataId", dataId);
        auditLog.put("dataVersion", dataVersion);
        auditLog.put("processName", processName);
        auditLog.put("incident", incident);
        auditLog.put("bpm", bpm);
        auditLog.put("initiatorName", initiatorName);
        auditLog.put("currentUserName", currentUserName);

        if (appResult == 0) {
            //审批状态为审批中
            FacadeHelper.addAduitLogV2(auditLog, auditModel);
        } else if (appResult == 1) {
            //审批状态为审批完成-流程结束
            OperationResult audit = SaveServiceHelper.saveOperate("audit", entityName, new DynamicObject[]{dynamicObject}, operateOption);//调用审核操作
            boolean success = audit.isSuccess();
            if (success) {
                //记录审批日志
                FacadeHelper.addAduitLogV2(auditLog, auditModel);
                //审核通过的单据直接变为等待付款
                //付款申请在调用推送G6时变为等待付款；资金计划和资金计划调整只有已审核状态，没有等待付款
                if (entityName != null && (entityName.equals("er_dailyloanbill"))) {
                    //借款单
                    QFilter[] a1 = new QFilter[]{new QFilter("billno", "=", dataId)};//单据信息：通过编码和实例号查询单据信息
                    DynamicObject dynamicObject1 = BusinessDataServiceHelper.loadSingle(entityName, a1);
                    boolean qeug_istog6 = dynamicObject1.getBoolean("qeug_istog6");//是否传至G6
                    if (qeug_istog6) {
                        //借款单推送G6成功再变为等待付款
                        dynamicObject.set("billstatus", "F");//单据状态
                        SaveServiceHelper.saveOperate(entityName, new DynamicObject[]{dynamicObject}, OperateOption.create());
                    } else {
                        ApprovalResultV2Result.setSuccess(true);
                        ApprovalResultV2Result.setData("操作成功,BPM审批流程结束,但单据推送G6失败,请联系开发人员进行排查！");

                        return CustomApiResult.success(ApprovalResultV2Result);
                    }
                }
            } else {
                //如果审核不成功，输出错误原因
                String message = null;
                for (IOperateInfo errInfo : audit.getAllErrorOrValidateInfo()) {
                    message = errInfo.getMessage();
                }
                ApprovalResultV2Result.setSuccess(false);
                ApprovalResultV2Result.setData(message);

                return CustomApiResult.success(ApprovalResultV2Result);
            }
        } else if (appResult == 3) {
            //审批状态为审批不同意-流程终止
            dynamicObject.set("qeug_processinstance", "");//bpm流程实例清空
            OperationResult noapprive = SaveServiceHelper.saveOperate("noapprive", entityName, new DynamicObject[]{dynamicObject}, operateOption);//调用审核不通过操作
            boolean success = noapprive.isSuccess();
            if (success) {
                //记录审批日志
                FacadeHelper.addAduitLogV2(auditLog, auditModel);
            } else {
                //如果审核不成功，输出错误原因
                String message = null;
                for (IOperateInfo errInfo : noapprive.getAllErrorOrValidateInfo()) {
                    message = errInfo.getMessage();
                }
                ApprovalResultV2Result.setSuccess(false);
                ApprovalResultV2Result.setData(message);

                return CustomApiResult.success(ApprovalResultV2Result);
            }
        }

        //中途未不成功，便返回成功结果
        ApprovalResultV2Result.setSuccess(true);
        ApprovalResultV2Result.setData("操作成功");

        return CustomApiResult.success(ApprovalResultV2Result);
    }
}

